package com.ys.shardingjdbcdemo.goods.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @program: sharding-jdbc-demo
 * @description: Goods分表策略
 * @author: Henry
 * @create 2020-06-07 17:30
 **/
@Component
public class ModTableShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection,
                             PreciseShardingValue<Long> preciseShardingValue) {
        String[] tables = collection.toArray(new String[0]);
        int index;
        if (preciseShardingValue.getValue() % 2 == 0) {
            // 偶数
            if (preciseShardingValue.getValue() % 4 == 0) {
                // 4, 8, 12
                index = 1;
            } else {
                // 2, 6, 10
                index = 0;
            }
        } else {
            // 奇数
            if (preciseShardingValue.getValue() % 4 == 1) {
                // 1, 5, 9
                index = 0;
            } else {
                // 3, 7, 11
                index = 1;
            }
        }
        return tables[index];
    }
}

